package com.xy.webadmin.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xy.common.core.object.TokenData;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

import static com.xy.common.core.constant.GlobalDeletedFlag.NORMAL;


@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 默认值为当前时间
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 默认值为当前时间
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); // 默认值为当前时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 默认值为当前时间
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, NORMAL); //逻辑删除
        TokenData tokenData = TokenData.takeFromRequest();
        if (tokenData != null) {
            Long userId = tokenData.getUserId();
            this.strictInsertFill(metaObject, "companyId", Long.class, TokenData.takeFromRequest().getDeptId()); // 默认值为当前时间
            this.strictInsertFill(metaObject, "deptId", Long.class, TokenData.takeFromRequest().getDeptId()); // 默认值为当前时间
            // 插入时填充 create_user_id 和 create_time
            this.strictInsertFill(metaObject, "createUserId", Long.class, userId); // 默认值为 0
            // 插入时也填充 update_user_id 和 update_time
            this.strictInsertFill(metaObject, "updateUserId", Long.class, userId); // 默认值为 0
            this.strictInsertFill(metaObject, "sysUserId", Long.class, userId); // 默认值为 0

        } else {
            // 插入时填充 create_user_id 和 create_time
            this.strictInsertFill(metaObject, "createUserId", Long.class, 0L); // 默认值为 0
            // 插入时也填充 update_user_id 和 update_time
            this.strictInsertFill(metaObject, "updateUserId", Long.class, 0L); // 默认值为 0

            this.strictInsertFill(metaObject, "companyId", Long.class, 0L); // 默认值为当前时间

            this.strictInsertFill(metaObject, "deptId", Long.class, 0L); // 默认值为当前时间
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        TokenData tokenData = TokenData.takeFromRequest();

        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); // 默认值为当前时间
        // 更新时填充 update_user_id 和 update_time
        if (tokenData != null) {

            this.strictUpdateFill(metaObject, "updateUserId", Long.class, tokenData.getUserId()); // 默认值为 0

        } else {

            this.strictUpdateFill(metaObject, "updateUserId", Long.class, 0L); // 默认值为 0

        }


    }
}